'''
Author: WuFeng <763467339@qq.com>
Date: 2024-11-20 20:21:16
LastEditTime: 2024-11-20 20:21:16
LastEditors: WuFeng <763467339@qq.com>
Description: pdf 拆分
FilePath: \markdown-magic\python\service\pdfSplit.py
Copyright 版权声明
'''
import PyPDF2

def split_pdf(input_pdf_path, output_folder):
    # 打开PDF文件
    with open(input_pdf_path, 'rb') as file:
        reader = PyPDF2.PdfReader(file)
        
        # 获取总页数
        num_pages = len(reader.pages)
        
        # 遍历每一页
        for page_num in range(num_pages):
            # 创建一个新的PDF写入对象
            writer = PyPDF2.PdfWriter()
            # 添加当前页到写入对象
            writer.add_page(reader.pages[page_num])
            
            # 构造输出文件名
            output_filename = f"{output_folder}/page_{page_num + 1}.pdf"
            
            # 写入到新的PDF文件
            with open(output_filename, 'wb') as output_file:
                writer.write(output_file)

# # 使用示例
# input_pdf = "example.pdf"  # 输入的PDF文件路径
# output_dir = "./output"   # 输出目录

# # 如果输出目录不存在，则创建
# import os
# if not os.path.exists(output_dir):
#     os.makedirs(output_dir)

# split_pdf(input_pdf, output_dir)